package com.beney.messageHandler;

import com.beney.codec.MessagePacket;
import com.beney.message.MessageHandler;
import com.beney.message.bizz.ChatRedirectReq;
import com.beney.message.bizz.ChatSendResp;
import com.beney.message.bizz.ChatSendToAllReq;
import com.beney.server.ChannelManager;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ChatSendToAllHandler implements MessageHandler<ChatSendToAllReq> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ChannelManager channelManager;

    @Override
    public void handle(Channel ch, ChatSendToAllReq message) {
        // TODO: 错误判断逻辑
        ChatSendResp resp = new ChatSendResp()
                .setMsgId(message.getMsgId())
                .setCode(ChatSendResp.CODE_SUCCESS);
        ch.writeAndFlush(resp);

        // 广播消息
        ChatRedirectReq req = new ChatRedirectReq()
                .setFromUser(message.getFromUser())
                .setContent(message.getContent());
        channelManager.sendAll(new MessagePacket(ChatRedirectReq.TYPE, req));
    }

    @Override
    public String messageType() {
        return ChatSendToAllReq.TYPE;
    }
}
